<template>
  <div class="p-2">

    <!-- 容器 -->
    <div style="width: 70%">
      <!-- el-form 包裹整个表格 -->
      <el-form ref="formRef" :model="data" :rules="rules" label-width="auto">
        <!-- 开头欢迎语 -->
        <div class="label-table-container">
          <div class="label-wrapper">
            <label class="table-label">开头欢迎语</label>
          </div>
          <!-- 右侧表格及设置区域 -->
          <div class="table-settings-wrapper">
            <!-- 表格 -->
            <el-table :data="data?.welcomeMsg?.msg" style="width: 100%;" border>
              <!-- 序号列 -->
              <el-table-column type="index" width="50"></el-table-column>
              <!-- 欢迎语内容 -->
              <el-table-column label="欢迎语内容">
                <template #default="scope">
                  <el-form-item :prop="'welcomeMsg.msg.' + scope.$index" :rules="rules.welcomeMsg">
                    <el-input v-model="data.welcomeMsg.msg[scope.$index]" placeholder="请输入欢迎语" type="textarea"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- 操作 -->
              <el-table-column label="操作" width="60">
                <template #default="scope">
                  <el-tooltip content="删除" placement="top">
                    <el-button link type="primary" icon="Delete" @click="handleWelcomeMsgDelete(scope.$index)"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <!-- 设置区域：字体颜色、加粗、新增按钮 -->
            <div class="settings-area" v-if="data?.welcomeMsg">
              <div class="flex gap-6 mb-3 flex-wrap">
                <div class="flex items-center">
                  <span class="bottom-body-title mr-2">字体颜色</span>
                  <el-color-picker v-model="data.welcomeMsg.fontColor"></el-color-picker>
                </div>
                <div class="flex items-center">
                  <span class="bottom-body-title mr-2">字体加粗</span>
                  <el-radio-group v-model="data.welcomeMsg.fontWeight">
                    <el-radio label="0">否</el-radio>
                    <el-radio label="1">是</el-radio>
                  </el-radio-group>
                </div>
              </div>
              <el-button @click="handleWelcomeMsgButton" type="primary">新增欢迎语</el-button>
            </div>
          </div>
        </div>

        <!-- 对话问答 -->
        <div class="label-table-container">
          <div class="label-wrapper">
            <label class="table-label">对话问答</label>
          </div>
          <!-- 右侧表格及设置区域 -->
          <div class="table-settings-wrapper">
            <div class="dialog-item" v-for="(item,index) in data?.dialogContent?.content" :key="index">
              <label class="dialog-item-title">对话-{{index+1}}</label><!-- 对话标题容器 -->
              <div class="dialog-title-container" :key="index">
                <!-- 标签容器 -->
                <div class="label-container">对话标题</div>
                <!-- 输入框与操作按钮容器 -->
                <div class="input-actions-container">
                  <!-- 表单项：对话标题 -->
                  <el-form-item :prop="`dialogContent.content.${index}.title`" :rules="rules.dialogContent" class="flex-1" >
                    <el-input v-model="item.title" placeholder="请输入对话标题" type="textarea" :rows="2" class="title-textarea" />
                  </el-form-item>
                  <!-- 删除按钮 -->
                  <el-tooltip content="删除对话" placement="top">
                    <el-button link type="primary" icon="Delete" @click="handleDialogDelete(index)" />
                  </el-tooltip>
                </div>
              </div>
              <!-- 新增答案按钮 -->
              <div class="dialog-answers-btn">
                <!-- 设置区域：字体颜色、加粗、新增按钮 -->
                <div class="settings-area">
                  <div class="flex gap-6 mb-3 flex-wrap items-center">
                    <div class="flex items-center">
                      <span class="bottom-body-title mr-2">字体颜色</span>
                      <el-color-picker v-model="item.fontColor"></el-color-picker>
                    </div>
                    <div class="flex items-center">
                      <span class="bottom-body-title mr-2">字体加粗</span>
                      <el-radio-group v-model="item.fontWeight">
                        <el-radio label="0">否</el-radio>
                        <el-radio label="1">是</el-radio>
                      </el-radio-group>
                    </div>
                  </div>
                </div>
                <el-button size="small" type="primary" @click="handleDialogAnswerAdd(item)">新增答案</el-button>
              </div>
              <!-- 表格 -->
              <el-table :data="item.answers" style="width: 100%;" border>
                <!-- 序号列 -->
                <el-table-column width="80">
                  <template #default="scope">
                    答案-{{scope.$index + 1}}
                  </template>
                </el-table-column>
                <!-- 答案内容 -->
                <el-table-column label="答案内容">
                  <template #default="scope">
                    <el-form-item :prop="`dialogContent.content.${index}.answers.${scope.$index}.answer`" :rules="rules.dialogContentAnswer">
                      <el-input v-model="item.answers[scope.$index].answer" placeholder="请输入答案"/>
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- 事件设置 -->
                <el-table-column label="事件设置">
                  <template #default="scope">
                    <el-form-item :prop="`dialogContent.content.${index}.answers.${scope.$index}.eventSet`" :rules="rules.dialogContentEvent" >
                      <el-select v-model="item.answers[scope.$index].eventSet"
                                 placeholder="请选择事件"
                                 @change="item.answers[scope.$index].replyContent = undefined"
                      >
                        <el-option v-for="option in events" :key="option.value" :label="option.label" :value="option.value" />
                      </el-select>
                    </el-form-item>
                    <el-form-item v-if="['1', '2'].includes(scope.row.eventSet)"
                      :prop="`dialogContent.content.${index}.answers.${scope.$index}.replyContent`" :rules="rules.replyContent" >
                      <el-input v-model="item.answers[scope.$index].replyContent" placeholder="请输入回复内容"/>
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- 操作 -->
                <el-table-column label="操作" width="60">
                  <template #default="scope">
                    <el-tooltip content="删除" placement="top">
                      <el-button link type="primary" icon="Delete" @click="handleDialogAnswerDelete(item,scope.$index)"></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 设置区域：新增按钮 -->
            <div class="settings-area" v-if="data?.dialogContent">
              <el-button @click="handleContentButton" type="primary">新增对话内容</el-button>
            </div>
          </div>
        </div>

        <!-- 结束内容 -->
        <div class="label-table-container">
          <div class="label-wrapper">
            <label class="table-label">结束内容</label>
          </div>
          <!-- 右侧表格及设置区域 -->
          <div class="table-settings-wrapper">
            <label style="font-size: 12px;color:#c0c0c0">如果“对话问答”版块最后一个对话选择“继续下一步”的时候，请设置“结束内容”版块</label>
            <!-- 表格 -->
            <el-table :data="data?.endContent?.contents" style="width: 100%;" border>
              <!-- 序号列 -->
              <el-table-column type="index" width="50"></el-table-column>
              <!-- 结束内容 -->
              <el-table-column label="结束内容">
                <template #default="scope">
                  <el-form-item :prop="`endContent.contents.${scope.$index}.content`" :rules="rules.endContent">
                    <el-input v-model="data.endContent.contents[scope.$index].content" placeholder="请输入结束内容" type="textarea"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- 事件 -->
              <el-table-column label="事件设置">
                <template #default="scope">
                  <el-form-item :prop="`endContent.contents.${scope.$index}.eventSet`" :rules="rules.endContentEvent" >
                    <el-select v-model="data.endContent.contents[scope.$index].eventSet" placeholder="请选择事件" >
                      <el-option v-for="option in endEvents" :key="option.value" :label="option.label" :value="option.value" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- 操作 -->
              <el-table-column label="操作" width="60">
                <template #default="scope">
                  <el-tooltip content="删除" placement="top">
                    <el-button link type="primary" icon="Delete" @click="handleEndContentDelete(scope.$index)"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <!-- 设置区域：字体颜色、加粗、新增按钮 -->
            <div class="settings-area" v-if="data?.endContent">
              <div class="flex gap-6 mb-3 flex-wrap">
                <div class="flex items-center">
                  <span class="bottom-body-title mr-2">字体颜色</span>
                  <el-color-picker v-model="data.endContent.fontColor"></el-color-picker>
                </div>
                <div class="flex items-center">
                  <span class="bottom-body-title mr-2">字体加粗</span>
                  <el-radio-group v-model="data.endContent.fontWeight">
                    <el-radio label="0">否</el-radio>
                    <el-radio label="1">是</el-radio>
                  </el-radio-group>
                </div>
              </div>
              <el-button @click="handleEndContentButton" type="primary">新增结束追加</el-button>
            </div>
          </div>
        </div>


        <!-- 对话按钮颜色 -->
        <div class="label-table-container-other">
          <div class="label-wrapper-other">
            <label class="table-label-other">对话按钮颜色</label>
          </div>
          <!-- 右侧表格及设置区域 -->
          <div class="table-settings-wrapper-other" v-if="data">
            <el-row>
              <el-col :span="8">
                <el-form-item label="边框">
                  <el-color-picker v-model="data.dialogBtn.frameColor"></el-color-picker>
                  <el-button type="primary" text @click="data.dialogBtn.frameColor = defaultColor">重置</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="按钮">
                  <el-color-picker v-model="data.dialogBtn.btnColor"></el-color-picker>
                  <el-button type="primary" text @click="data.dialogBtn.btnColor = defaultColor">重置</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="字体">
                  <el-color-picker v-model="data.dialogBtn.fontColor"></el-color-picker>
                  <el-button type="primary" text @click="data.dialogBtn.fontColor = defaultColor">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <!-- 跳转按钮颜色 -->
        <div class="label-table-container-other">
          <div class="label-wrapper-other">
            <label class="table-label-other">跳转按钮颜色</label>
          </div>
          <!-- 右侧表格及设置区域 -->
          <div class="table-settings-wrapper-other" v-if="data">
            <el-row>
              <el-col :span="8">
                <el-form-item label="边框">
                  <el-color-picker v-model="data.skipBtn.frameColor"></el-color-picker>
                  <el-button type="primary" text @click="data.skipBtn.frameColor = defaultColor">重置</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="按钮">
                  <el-color-picker v-model="data.skipBtn.btnColor"></el-color-picker>
                  <el-button type="primary" text @click="data.skipBtn.btnColor = defaultColor">重置</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="字体">
                  <el-color-picker v-model="data.skipBtn.fontColor"></el-color-picker>
                  <el-button type="primary" text @click="data.skipBtn.fontColor = defaultColor">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <!-- 跳转按钮文案 -->
        <div class="label-table-container-other">
          <div class="label-wrapper-other">
            <label class="table-label-other">跳转按钮文案</label>
          </div>
          <!-- 右侧表格及设置区域 -->
          <div class="table-settings-wrapper-other" v-if="data">
            <el-form-item prop="skipBtn.text" :rules="rules.skipBtnText">
              <el-input v-model="data.skipBtn.text" placeholder="请输入跳转按钮文案" clearable/>
            </el-form-item>
          </div>
        </div>
        <!-- 跳转按钮动画 -->
        <div class="label-table-container-other">
          <div class="label-wrapper-other">
            <label class="table-label-other">跳转按钮动画</label>
          </div>
          <!-- 右侧表格及设置区域 -->
          <div class="table-settings-wrapper-other" v-if="data">
            <el-form-item>
              <el-radio-group v-model="data.skipBtn.animation">
                <el-radio label="0">无动画</el-radio>
                <el-radio label="1">放大缩小</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
//默认颜色
const defaultColor = ref('#4173ff');
export interface DialogModeSetVo {
  //开头欢迎语
  welcomeMsg?: {
    msg?:string[],//欢迎语
    fontColor?:string,//字体颜色
    fontWeight?:string,//字体加粗 0.否 1.是
  };
  //对话问答
  dialogContent?: {
    content: DialogContentVo[],//对话内容
  },
  //结束内容
  endContent?:{
    contents:DialogEndVo[],//结束内容
    fontColor?:string,//字体颜色
    fontWeight?:string,//字体加粗 0.否 1.是
  },
  //对话按钮
  dialogBtn?:{
    frameColor?:string,//边框颜色
    btnColor?:string,//按钮颜色
    fontColor?:string,//字体颜色
  },
  //跳转按钮
  skipBtn?:{
    text?:string,//按钮文字
    animation?:string,//跳转按钮动画 0.无动画 1.放大缩小
    frameColor?:string,//边框颜色
    btnColor?:string,//按钮颜色
    fontColor?:string,//字体颜色
  }
}
//对话内容
export interface DialogContentVo {
  title?: string,//对话标题
  answers?:DialogAnswerVo[],
  fontColor?:string,//字体颜色
  fontWeight?:string,//字体加粗 0.否 1.是
}
//对话答案
export interface DialogAnswerVo {
  answer?:string,//对话答案
  eventSet?:string,//事件设置 0.继续下一步 1.回复内容并下一步 2.结束并回复内容(不显示跳转按钮) 3.点击直接跳转(点击答案跳转)
  replyContent?:string,//回复内容
}
//结束内容
export interface DialogEndVo {
  content?:string,//结束内容
  eventSet?:string,//事件设置 0.结束并显示跳转按钮 1.继续下一句
}

/**
 * 表格数据
 */
const data = ref<DialogModeSetVo>();
const formRef = ref<ElFormInstance>();

const rules = {
  welcomeMsg: [
    { required: true, message: '请输入欢迎语内容', trigger: ['blur', 'change'] }
  ],
  dialogContent: [
    { required: true, message: '请输入对话标题', trigger: ['blur', 'change'] }
  ],
  dialogContentAnswer: [
    { required: true, message: '请输入答案内容', trigger: ['blur', 'change'] }
  ],
  dialogContentEvent: [
    { required: true, message: '请选择事件', trigger: ['blur', 'change'] }
  ],
  replyContent:[
    { required: true, message: '请输入回复内容', trigger: ['blur', 'change'] }
  ],
  endContent: [
    { required: true, message: '请输入结束内容', trigger: ['blur', 'change'] }
  ],
  endContentEvent:[
    { required: true, message: '请选择事件', trigger: ['blur', 'change'] }
  ],
  skipBtnText:[
    { required: true, message: '请输入跳转按钮文字', trigger: ['blur', 'change'] }
  ],

};
//对话内容事件数组
const events = [
  {
    value: '0',
    label: '继续下一步',
    desc: '用户点击答案后，直接进入下一个问题，不显示回复文本。'
  },
  {
    value: '1',
    label: '回复内容并继续下一步',
    desc: '先显示设定的回复内容，然后自动进入下一个问题。'
  },
  {
    value: '2',
    label: '结束并回复内容(不显示跳转按钮)',
    desc: '显示回复内容后流程结束，不提供跳转按钮。'
  },
  {
    value: '3',
    label: '点击直接跳转(答案即跳转)',
    desc: '点击答案立即跳转到链接或结束对话，不展示回复内容。'
  }
];
//结束内容事件数组
const endEvents = [
  {
    value: '0',
    label: '结束并显示跳转按钮',
  },
  {
    value: '1',
    label: '继续下一句',
  },
];

const props = defineProps({
  modelValue: Object,
});
onMounted(() => {
// 在初始化时设置 formData
  Object.assign(data, props.modelValue);
  // 确保 data.value 存在，避免空值错误
  if (!data.value) {
    data.value = {};
  }

  // 如果 welcomeMsg 不存在，则进行初始化
  if (!data.value.welcomeMsg) {
    data.value.welcomeMsg = {
      msg: [],
      fontColor: '#000000',
      fontWeight: '0',
    };
  }
  //如果 dialogContent 不存在，则进行初始化
  if (!data.value.dialogContent) {
    data.value.dialogContent = {
      content: [],
    }
  }
  //如果 endContent 不存在，则进行初始化
  if (!data.value.endContent) {
    data.value.endContent = {
      contents: [],
      fontColor: '#000000',
      fontWeight: '0',
    }
  }
  //如果 dialogBtn 不存在，则进行初始化
  if (!data.value.dialogBtn) {
    data.value.dialogBtn = {
      frameColor: defaultColor.value,
      btnColor: defaultColor.value,
      fontColor: '#FFFFFF',
    }
  }
  //如果 skipBtn 不存在，则进行初始化
  if (!data.value.skipBtn) {
    data.value.skipBtn = {
      text: '',
      animation: '0',
      frameColor: defaultColor.value,
      btnColor: defaultColor.value,
      fontColor: '#FFFFFF',
    }
  }
});

const emit = defineEmits(['update:modelValue','confirmCallBack']);
watch(data, (newVal, oldVal) => {
  emit('update:modelValue', newVal);
  emit('confirmCallBack', newVal);
}, { deep: true, immediate: true });

watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    if(data.value){
      Object.assign(data.value, newVal);
    }
  }
}, { deep: true, immediate: true });

/**
 * 新增按钮点击事件
 */
const handleWelcomeMsgButton = () => {
  // 向 msg 数组添加一个新的空字符串
  data.value.welcomeMsg.msg.push('');
}

/** 删除按钮操作 */
const handleWelcomeMsgDelete = async (index: number) => {
  data.value.welcomeMsg.msg.splice(index, 1);
}

/**
 * 新增对话内容按钮点击事件
 */
const handleContentButton = () => {
  // 向 dialogContent 内容数组添加一个新的空字符串
  data.value.dialogContent.content.push({
    fontColor: '#000000',
    fontWeight: '0',
  })
}

/**
 * 删除对话按钮点击事件
 * @param index
 */
const handleDialogDelete = (index: number) => {
  data.value.dialogContent.content.splice(index, 1);
}
/**
 * 新增对话内容答案
 */
const handleDialogAnswerAdd = (item: DialogContentVo) => {
  //获取答案列表如果为空则初始化
  item.answers = item.answers || [];
  item.answers.push({})
}
/**
 * 删除对话内容答案
 * @param item
 * @param index
 */
const handleDialogAnswerDelete = (item: DialogContentVo, index: number) => {
  item.answers.splice(index, 1);
}
/**
 * 新增结束内容按钮点击事件
 */
const handleEndContentButton = () => {
  // 向 endContent 内容数组添加一个新的空字符串
  data.value.endContent.contents.push({});
}
/**
 * 删除结束内容按钮点击事件
 * @param index
 */
const handleEndContentDelete = (index: number) => {
  data.value.endContent.contents.splice(index, 1);
}

const validateForm = () => {
  return new Promise((resolve, reject) => {
    if (!formRef.value) {
      reject(new Error('表单引用不存在'));
      return;
    }
    formRef.value.validate(valid => {
      if (valid) {
        resolve(true);
      } else {
        reject(new Error('问答设置表单填写不完整'));
      }
    });
  });
};

defineExpose({
  validateForm,
});
</script>

<style scoped>
/* 容器：label、table 和 settings-area 的父容器 */
.label-table-container {
  display: flex;
  align-items: flex-start; /* 顶部对齐 */
  gap: 16px; /* label 和右侧内容之间的间距 */
  margin-bottom: 50px;
}

/* label 的包装器 */
.label-wrapper {
  min-width: fit-content; /* 确保宽度只够容纳文本 */
}

.table-label {
  color: var(--el-text-color-regular); /* 使用 Element Plus 的 --el-text-color-regular */
  font-weight: 1000; /* 可选：比普通文本稍重 */
  white-space: nowrap; /* 防止换行 */
  margin-top: 8px; /* 微调垂直位置，与表格第一行对齐 */
  font-size: 14px; /* 可选：与表单文本一致 */
}

/* table 和 settings-area 的共同包装器 */
.table-settings-wrapper {
  width: 100%; /* 占据剩余空间 */
}

/* 设置区域样式 */
.settings-area {
  margin-top: 16px; /* 与表格之间留出间距 */
  width: 100%; /* 明确占满整行 */
  font-size: 12px;
}

.dialog-title-container {
  display: flex;
  align-items: center; /* 垂直居中 */
  padding: 8px; /* 内边距 */
  border: 1px solid #dcdfe6; /* 边框 */
  /* 设置背景色为 CSS 变量 --tableHeaderBg */
  background-color: var(--tableHeaderBg);
}

.label-container {
  width: 90px; /* 固定宽度，可根据实际需要调整 */
  text-align: right; /* 右对齐文本 */
  padding-right: 10px; /* 右内边距 */
  display: flex;
  align-items: center; /* 垂直居中 */
  font-size: 13px;
  color: var(--tableHeaderTextColor);
  font-weight: 1000;
}

/* 右侧：输入框 + 按钮 容器 */
.input-actions-container {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  padding: 4px 8px;
}

/* 表单项：去除默认 margin，占满空间 */
.input-actions-container .el-form-item {
  margin-bottom: 0 !important;
  flex: 1;
  display: flex;
  height: 100%;
}

/* 输入框样式控制 */
.input-actions-container .el-input {
  width: 100%;
}

.input-actions-container .title-textarea .el-textarea__inner {
  min-height: 36px !important;
  line-height: 1.5;
  padding: 6px 10px;
  font-size: 14px;
  resize: vertical;
}

/* 删除按钮微调 */
.input-actions-container .el-button {
  padding: 5px;
}
.dialog-item {
  margin-bottom: 20px; /* 每个对话块之间的间距 */
}

/* 最后一个不需要下边距 */
.dialog-item:last-child {
  margin-bottom: 0;
}

.dialog-item-title{
  font-size: 14px;
  font-weight: 500;
}
/**新增答案按钮*/
.dialog-answers-btn{
  height: 50px;
  display: flex;
  align-items: center; /* 垂直居中 */
  padding: 8px; /* 内边距 */
  border-left: 1px solid #dcdfe6; /* 边框 */
  border-right: 1px solid #dcdfe6; /* 边框 */
  background-color: #fff; /* 背景颜色 */
  gap: 12px;
}


/* 外层容器：使用 Flex 布局，垂直居中 */
.label-table-container-other {
  display: flex;
  align-items: center;        /* 垂直居中对齐 */
  gap: 16px;                  /* 推荐：统一间距，比 margin 更现代 */
  min-height: 40px;           /* 可选：保证最小高度，避免压缩 */
  flex-wrap: wrap;            /* 可选：响应式换行 */
}
/* 标签区域：保持左对齐，可设置固定宽度或最小宽度 */
.label-wrapper-other {
  flex-shrink: 0;             /* 防止标签被压缩 */
  white-space: nowrap;        /* 防止标签文字换行 */
}

/* 表单标签样式（可选美化） */
.table-label-other {
  font-weight: 1000;
  font-size: var(--el-form-label-font-size);
  color: var(--el-text-color-regular);
}


/* 设置区域：确保 el-row 正确使用 Flex 布局 */
.table-settings-wrapper-other .el-form-item {
  margin-bottom: 0 !important; /* 防止 el-form-item 添加额外下边距 */
}

/* el-row 启用 flex 并垂直居中 */
.table-settings-wrapper-other .el-row {
  display: flex;
  align-items: center;        /* 关键：让每一行内的列垂直居中 */
  flex-wrap: wrap;            /* 支持响应式换行 */
  width: 100%;
}

/* 可选：控制每个颜色选择器区域的间距 */
.table-settings-wrapper-other .el-col {
  display: flex;
  align-items: center;
  gap: 8px;                   /* label 和 picker 之间的间距 */
}
</style>
